package com.heima.reggie.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.heima.reggie.bean.Category;
import com.heima.reggie.bean.PageParam;
import com.heima.reggie.common.R;
import com.heima.reggie.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.logging.Level;

@RestController
@RequestMapping("/category")
@Api(tags = "分类管理")
public class CategoryController {
    @Autowired
    private CategoryService service;

    @ApiOperation(value ="根据条件分页查询")
    @GetMapping
    public R selectByPage(PageParam pageParam) {
        IPage<Category> page = service.selectByPage(pageParam);
        if (page != null) {
            return R.success(page);
        } else {
            return R.error("查询失败！");
        }
    }

    @PostMapping("/delete")
    @ApiOperation(value ="删除分类")
    public R deleteById(@RequestBody Category category) {
        int i = service.deleteById(category);
        if (i > 0) {
            return R.success("删除成功！");
        } else {
            return R.error("删除失败！");
        }
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping
    @ApiOperation(value ="添加分类")
    public R add(@RequestBody Category category) {
        int add = service.add(category);
        if (add > 0) {
            return R.success("添加成功！");
        } else {
            return R.error("添加失败！");
        }
    }

    @PutMapping
    @ApiOperation(value ="更新分类")
    public R upadate(@RequestBody Category category) {
        int update = service.update(category);
        if (update > 0) {
            return R.success("更新成功！");
        } else {
            return R.error("更新失败！");
        }
    }

    @GetMapping("/list/{id}")
    @ApiOperation(value ="根据分类id查询分类")
    public R selectDishList(@PathVariable int id) {
        List<Category> categories = service.selectDishList(id);
        if (categories != null) {
            return R.success(categories);
        } else {
            return R.error("查询失败！");
        }
    }
    @GetMapping("list")
    @ApiOperation(value ="查询分类")
    public R select() {
        List<Category> list=service.select();
        if ( list!= null) {
            return R.success(list);
        } else {
            return R.error("查询失败！");
        }
    }
}
